﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace UltralightTransformer
{
	public class Transform
	{
		private static Jurassic.ScriptEngine engine;
		private static Regex CrLf;
		private static Regex Tab;

		private string linefeed = ((char)10).ToString();
		private const string fourspaces = "    ";

		public Transform()
		{
			if (engine == null)
			{
				engine = new Jurassic.ScriptEngine();
				//engine.ForceStrictMode = true;
				engine.Execute(JavascriptResource.ultralight_js); // this resource is the same as jquery.ultralight.markup.js
				engine.Execute("var converter = new Ultralight.converter;");
				engine.Execute("var makeHtml = converter.makeHtml;");
			}
			if (CrLf == null)
			{
				CrLf = new Regex(@"\r\n");
			}
			if (Tab == null)
			{
				Tab = new Regex(@"\t");
			}
		}

		public string MakeHTML(string text)
		{
			if (string.IsNullOrEmpty(text)) return "";

			// encoding (it's faster to do this here than in Javascript)
			text = text.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
			text = CrLf.Replace(text, linefeed);
			text = Tab.Replace(text, fourspaces);

			// call our Javascript makeHtml function and skip the encoding step
			return engine.CallGlobalFunction<string>("makeHtml", text, true); // makeHtml(text, true);  
		}
	}
}
